package com.cjq.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cjq.domain.Questionnaire;
import com.cjq.utils.Constant;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Calendar;
import java.util.Date;

import java.util.concurrent.TimeUnit;

/**
 * @author junqiancai@foxmail.com
 * @since 2021/6/22 1:15
 */
@Service
public class QuestConsumer {
    @Autowired
    private QuestionnaireService service;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private boolean checkRedisNRS(Integer userId){
        //构造key
        final Calendar today = Calendar.getInstance();
        today.set(Calendar.HOUR_OF_DAY,0);
        today.set(Calendar.MINUTE,0);
        today.set(Calendar.SECOND,0);
        today.set(Calendar.MILLISECOND,0);
        String key = Constant.NON_REPEATED_SUBMIT+today.getTimeInMillis()+"-"+userId;
        if(Boolean.TRUE.equals(redisTemplate.hasKey(key)))
            return Boolean.TRUE.equals(redisTemplate.delete(key));
        return false;
    }
    private void putResInRedis(Integer userId, String value){
        redisTemplate.opsForValue().set(Constant.POLLING_PREFIXED+userId,value, Duration.ofMinutes(3));
    }
    // 使用JmsListener配置消费者监听的队列，其中name是接收到的消息
    // SendTo 会将此方法返回的数据, 写入到 OutQueue 中去.
    //@SendTo("SQueue")
    @JmsListener(destination = "ActiveMQQueue",concurrency = "10")
    public void handleMessage(Questionnaire questionnaire) {
        if(!checkRedisNRS(questionnaire.getUserId())){
            //重复打卡时不能往redis中放标志位，并发请求时会覆盖掉redis中正确请求成功的标志
//            putResInRedis(questionnaire.getUserId(),Constant.POLLING_UNWANTED);
            return;
        }
        questionnaire.setClockInDate(new Date());
        Object addressJson = questionnaire.getAddressJson();
        Object dangerZoneJson = questionnaire.getDangerZoneJson();
        ObjectMapper om = new ObjectMapper();
        try {
            String address = om.writeValueAsString(addressJson);
            String dangerZone = om.writeValueAsString(dangerZoneJson);
            questionnaire.setAddress(address);
            questionnaire.setDangerZone(dangerZone);
            //看一下昨天有没有打卡
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH,-1);
            LambdaQueryWrapper<Questionnaire> wrapper = new LambdaQueryWrapper<Questionnaire>()
                    .eq(Questionnaire::getUserId,questionnaire.getUserId())
                    .eq(Questionnaire::getClockInDate, new java.sql.Date(calendar.getTimeInMillis()));
            Questionnaire lastQuest = service.getOne(wrapper);
            if(lastQuest!=null){
                questionnaire.setDuration(lastQuest.getDuration()+1);
            }
            else questionnaire.setDuration(1);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            putResInRedis(questionnaire.getUserId(),Constant.POLLING_FAIL);
        }
        service.save(questionnaire);
        putResInRedis(questionnaire.getUserId(),Constant.POLLING_SUCCESS);
    }
}
